import { defineStore } from "pinia";
import { STORE_PREFIX } from "@/utils/constant";
import { cloneDeep, intersectionBy, uniqBy } from "lodash-es";
import { reqChatContentList } from "@/api/main";

export const useServiceStore = defineStore(
  `${STORE_PREFIX}service_store`,
  () => {
    const status = ref<boolean>(false);
    const tabActive = ref(false);
    const serviceActive = ref(0);
    const serviceList = ref<ChatContentMo[]>([]);
    const serviceState = ref({
      Page: 1,
      PageSize: 200,
      TotalPage: 9999,
      Name: "",
      SortField: "time"
    });

    const getStatus = computed(() => status.value);
    const getServiceList = computed(() => serviceList.value);

    const setStatus = (b: boolean) => {
      status.value = b;
    };
    const setTabActive = (b: boolean) => {
      tabActive.value = b;
    };
    const setServiceActive = (b: number) => {
      serviceActive.value = b;
    };
    const actionServiceList = async (id?: string) => {
      try {
        const res = await reqChatContentList({
          Page: serviceState.value.Page,
          PageSize: serviceState.value.PageSize,
          SortField: serviceState.value.SortField,
          ...(serviceState.value.Name ? { Name: serviceState.value.Name } : {}),
          ...(serviceState.value.Name ? { Name: serviceState.value.Name } : {})
        });
        let oldList = cloneDeep(serviceList.value);
        const list = res.data.List || [];
        oldList = cloneDeep(intersectionBy(oldList, list, "UserId"));
        for (let i = 0; i < list.length; i++) {
          const oldItem = oldList.find(item => item.UserId == list[i].UserId);
          if (oldItem) {
            oldList[i] = {
              ...list[i],
              Count: oldItem.Count
            };
          } else {
            oldList.push({
              ...list[i],
              Count: id && id == list[i].UserId ? 1 : 0
            });
          }
        }
        serviceState.value.TotalPage = Math.ceil(res.data.Total / serviceState.value.PageSize);
        const uniqList = uniqBy(oldList, "UserId");
        serviceList.value = cloneDeep(uniqList);
      } catch (error) {
        console.log(error);
      }
    };
    const addService = (item: ChatContentMo) => {
      serviceList.value.push(item);
    };
    const removeService = (item: ChatContentMo) => {
      serviceList.value = cloneDeep(
        serviceList.value.filter((i: ChatContentMo) => i.UserId !== item.UserId)
      );
    };
    const updateServiceItem = (mo: ChatContentMo, flag: boolean = false) => {
      console.log(mo);
      const services = cloneDeep(serviceList.value);
      for (let i = 0; i < services.length; i++) {
        if (Number(services[i].UserId) == Number(mo.UserId)) {
          services[i] = cloneDeep({
            ...services[i],
            LastMsg: mo.LastMsg,
            LastMsgTime: mo.LastMsgTime,
            Count: flag ? 0 : (services[i].Count! as number) + 1
          });
          break;
        }
      }
      serviceList.value = cloneDeep(services);
    };
    watch(
      () => serviceList.value,
      val => {
        let flag = false;
        val.forEach(item => {
          if (item.Count! > 0) {
            flag = true;
          }
        });
        status.value = flag;
      }
    );
    return {
      status,
      tabActive,
      serviceActive,
      serviceList,
      serviceState,
      getStatus,
      getServiceList,
      setStatus,
      setTabActive,
      setServiceActive,
      addService,
      removeService,
      actionServiceList,
      updateServiceItem
    };
  },
  {
    persist: {
      storage: sessionStorage
    }
  }
);
